<?php

namespace app\pay\controller;

use app\common\exception\BusinessException;
use app\pay\logic\PayCallback;
use app\pay\service\AliPayService;

class AliPay extends Base
{
    /**
     * notify
     * @throws BusinessException
     */
    public function notify(): string
    {
        // 获取参数
        $data = $_POST;
        $appId = $this->request->param('appId', '');
        if (!$appId) {
            return '请求租户编号为空';
        }
        if (!$data) {
            throw new BusinessException('非法请求');
        }
        $signIsPass = (new AliPayService())->setAppId($appId)->checkSign($data);
        if (!$signIsPass) {
            throw new BusinessException('签名不正确');
        }

        // 订单处理
        $trade_no = $_POST['trade_no'] ?? '';
        $out_trade_no = $_POST['out_trade_no'] ?? '';
        if (!$out_trade_no || !$trade_no) {
            return '未获取到订单号';
        }

        // 查询订单数据
        try {
            (new PayCallback())->invoke($out_trade_no, $trade_no);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        // 返回
        return 'success';
    }
}
